package com.naqiang.electronicdictionary.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.naqiang.electronicdictionary.R;
import com.naqiang.electronicdictionary.adapter.FragmentAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Author by naqiang, Date on 2019\3\15 0015.
 * PS: Not easy to write code, please indicate.
 * 翻译主Fragment
 * 此Fragment利用Fragment+ViewPager实现在线翻译和离线翻译的左右切换
 */
public class TranslateFragment extends BaseFragment implements ViewPager.OnPageChangeListener {


    private TextView tv_topbar_title;
    private List<Fragment> list;
    private ViewPager vp_message;
    private FragmentAdapter adapter;
    private OnlineTranslateFragment onlineTranslateFragment;
    private OfflineTranslateFragment offlineTranslateFragment;

    @Override
    protected int setView() {
        return R.layout.fragment_translate;
    }

    @Override
    protected void initView(View view) {
        tv_topbar_title = view.findViewById(R.id.tv_topbar_title);
        vp_message = view.findViewById(R.id.vp_message);
        //初始化adapter
        adapter = new FragmentAdapter(getActivity().getSupportFragmentManager(), list);
        //将适配器和ViewPager结合
        vp_message.setAdapter(adapter);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        //建一个存放fragment的集合，并且把新的fragment放到集合中
        onlineTranslateFragment = new OnlineTranslateFragment();
        offlineTranslateFragment = new OfflineTranslateFragment();
        list = new ArrayList<Fragment>();
        list.add(onlineTranslateFragment);
        list.add(offlineTranslateFragment);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

        vp_message.setOnPageChangeListener(this);
    }

    @Override
    public void doWork() {
        tv_topbar_title.setText(getResources().getString(R.string.online));
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (onlineTranslateFragment != null) {
            onlineTranslateFragment.refreshLanguageChooser();
        }
    }

    @Override
    public void onPageSelected(int i) {
        if (adapter.getCurrentFragmentIndex() == 1) {
            tv_topbar_title.setText(getResources().getString(R.string.online));
            if (onlineTranslateFragment != null) {
                onlineTranslateFragment.refreshLanguageChooser();
            }
        }
        if (adapter.getCurrentFragmentIndex() == 0) {
            tv_topbar_title.setText(getResources().getString(R.string.offline));
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {
    }
}
